package com.teach.config.mvc.resolver;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.teach.R;
import com.teach.config.ConfigProperties;
import com.teach.exception.CodeException;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * <pre>
 * MVC控制器的异常统一处理类
 * 创建时间 ：	2019年12月2日 下午12:01:21
 * 当前版本：	V1.0
 * Copyright © 1998 - 2019 jlzhou.top. All Rights Reserved	
 * </pre>
 * @author J.L.Zhou
 *
 */
@ControllerAdvice
@Slf4j
public class CodeExceptionResolver {
	
	@Autowired
	private ConfigProperties config;
	
	@Autowired
	private ObjectMapper mapper;

	@ExceptionHandler(Exception.class)
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		RequestContext rc = new RequestContext(request);
		if(ex instanceof CodeException){
			CodeException ce = (CodeException)ex;
			ce.setMessage(rc.getMessage(ce.getMessage()));
		}
		
		log.debug("全局异常",ex);
		
		
		String err =request.getParameter(config.error.errorParameter);//需要展示错误页面视图名
		if(err==null){
			response.reset();
			response.setContentType("text/plain;charset=UTF-8");
			if(ex instanceof CodeException){
				CodeException ce = (CodeException)ex;
				try {
					response.getWriter().write(mapper.writeValueAsString(R.error(ce.getCode(), ce.getMessage())));
					response.getWriter().flush();
					response.getWriter().close();
				} catch (Exception e) {
					log.warn("响应输出异常", e);
				}
			}else{
				try {
					response.getWriter().write(mapper.writeValueAsString(R.error(0, ex.getMessage())));
					response.getWriter().flush();
					response.getWriter().close();
				} catch (Exception e) {
					log.warn("响应输出异常", e);
				}
			}
			return null;
		}else{
		
			ModelAndView view = new ModelAndView();
			view.setViewName(err.equals("")?config.error.viewName:err);
			view.addObject("ex", ex);
			return view;
		}
	}

}
